package com.tzy.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tzy.springboot.common.Result;
import com.tzy.springboot.entity.SystemLog;
import com.tzy.springboot.mapper.SystemLogMapper;
import com.tzy.springboot.service.ISystemLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/systemLog")
public class SystemLogController {

    @Autowired
    private ISystemLogService systemLogService;

    /**
     * 分页查询系统日志
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String level,
                           @RequestParam(defaultValue = "") String module) {

        IPage<SystemLog> page = new Page<>(pageNum, pageSize);
        QueryWrapper<SystemLog> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");

        // 按日志级别过滤
        if (!level.isEmpty()) {
            queryWrapper.eq("level", level);
        }

        // 按模块过滤
        if (!module.isEmpty()) {
            queryWrapper.like("module", module);
        }

        return Result.success(systemLogService.page(page, queryWrapper));
    }

    /**
     * 查看日志详情
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        SystemLog log = systemLogService.getById(id);
        return Result.success(log);
    }

    /**
     * 删除日志
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(systemLogService.removeById(id));
    }

    /**
     * 清空所有日志
     */
    @DeleteMapping("/clear")
    public Result clearAll() {
        QueryWrapper<SystemLog> queryWrapper = new QueryWrapper<>();
        return Result.success(systemLogService.remove(queryWrapper));
    }
}
